import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/utils/color.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';

class Copy extends StatefulWidget {
  final Function()? callBack;
  const Copy({super.key, required this.callBack});

  @override
  State<Copy> createState() => _CopyState();
}

class _CopyState extends State<Copy> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  // 1. 移除initState中的提前dispose，仅在此处初始化控制器
  TextEditingController controller = TextEditingController(); // 精灵名字输入框控制器
  TextEditingController wishController = TextEditingController(); // 目标输入框控制器

  // 语音识别核心变量
  final SpeechToText _speechToText = SpeechToText();
  bool _isSpeechAvailable = false;
  bool isRecord = false;
  String _recognizedText = '';

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);
    _initSpeech();
  }

  @override
  void dispose() {
    _controller.dispose();
    // 3. 仅在dispose生命周期中统一释放所有控制器，确保所有组件都已停止使用
    controller.dispose();
    wishController.dispose();
    super.dispose();
  }

  /// 初始化语音识别
  void _initSpeech() async {
    bool available = await _speechToText.initialize(
      onStatus: (status) => print('语音识别状态：$status'),
      onError: (error) => print('语音识别错误：$error'),
    );
    setState(() {
      _isSpeechAvailable = available;
    });
  }

  /// 开始语音识别
  void _startListening() async {
    if (!_isSpeechAvailable) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('语音识别不可用，请检查设备设置')),
      );
      return;
    }

    setState(() {
      isRecord = true;
      _recognizedText = '';
    });

    await _speechToText.listen(
      onResult: _onSpeechResult,
      localeId: 'zh_CN',
      partialResults: true,
      listenFor: const Duration(seconds: 20),
    );
  }

  /// 停止语音识别
  void _stopListening() async {
    await _speechToText.stop();

    setState(() {
      isRecord = false;
    });

    if (_recognizedText.isNotEmpty) {
      String finalText = _recognizedText;
      if (finalText.length > 8) {
        finalText = finalText.substring(0, 8);
      }
      wishController.text = finalText;
    }
  }

  /// 语音识别结果回调
  void _onSpeechResult(SpeechRecognitionResult result) {
    print('result$result');
    setState(() {
      _recognizedText = result.recognizedWords;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 精灵名字输入容器
        Container(
            width: 350,
            height: 470,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(24.px),
                border: Border.all(width: 1.px, color: hexColor('#666666'))),
            child: Column(children: [
              Container(
                width: 350,
                height: 60,
                decoration: BoxDecoration(
                  color: hexColor('#F5F5F5'),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(24.px),
                    topRight: Radius.circular(24.px),
                  ),
                ),
                child: Column(
                  children: [
                    Container(),
                    Container(
                      width: 200,
                      height: 60.px,
                      child: Focus(
                        onFocusChange: (hafocus) {
                          if (!hafocus) {
                            // SystemChrome.setEnabledSystemUIMode(
                            //     SystemUiMode.manual);
                            print('1${controller.text}');
                          }
                        },
                        child: TextField(
                          // 此时controller未被提前释放，可正常使用
                          controller: controller,
                          cursorColor: hexColor('#F04136'),
                          cursorWidth: 2.px,
                          decoration: InputDecoration(
                            filled: true,
                            fillColor: Colors.white,
                            contentPadding:
                                EdgeInsets.only(bottom: 0, left: 8, top: 10),
                            counterText: "",
                            hintText: '输入精灵名字',
                            hintMaxLines: 1,
                            focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: hexColor('#cccccc'),
                                  width: 1.px,
                                ),
                                borderRadius: BorderRadius.circular(16)),
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                color: hexColor('#cccccc'),
                                width: 1.px,
                              ),
                              borderRadius: BorderRadius.circular(10),
                            ),
                          ),
                          maxLength: 8,
                          maxLines: 1,
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              const SizedBox(height: 20),
            ])),

        // 长按语音识别按钮
        GestureDetector(
          onLongPressStart: (_) => _startListening(),
          onLongPressEnd: (_) => _stopListening(),
          onTap: widget.callBack,
          child: Container(
            margin: EdgeInsets.only(top: 30),
            child: Image.asset(
              isRecord
                  ? 'lib/assets/images/home/enter.png'
                  : 'lib/assets/images/home/genertate/no-enter.png',
              width: 350,
              height: 70,
            ),
          ),
        ),

        // 目标输入框
        Container(
          width: 350,
          height: 60.px,
          margin: EdgeInsets.only(top: 12),
          child: Focus(
            onFocusChange: (hafocus) {
              if (!hafocus) {
                // SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual);
                print('1${wishController.text}');
              }
            },
            child: TextField(
              controller: wishController,
              cursorColor: hexColor('#F04136'),
              cursorWidth: 2.px,
              decoration: InputDecoration(
                filled: true,
                fillColor: Colors.white,
                contentPadding: EdgeInsets.only(bottom: 0, left: 8, top: 10),
                counterText: "",
                hintText: '输入你的目标吧～',
                hintMaxLines: 1,
                focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: hexColor('#cccccc'),
                      width: 1.px,
                    ),
                    borderRadius: BorderRadius.circular(16)),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: hexColor('#cccccc'),
                    width: 1.px,
                  ),
                  borderRadius: BorderRadius.circular(16),
                ),
              ),
              maxLength: 8,
              maxLines: 1,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),
        )
      ],
    );
  }
}
